package com.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.constants.WeChatConstants;
import com.example.common.enums.CommonEnums;
import com.example.common.response.SystemResponse;
import com.example.common.utils.HttpServletRequestUtil;
import com.example.common.utils.JsonUtil;
import com.example.common.utils.JwtUtil;
import com.example.common.utils.WeChatUtil;
import com.example.system.dto.AuthorizedLoginDTO;
import com.example.system.entity.User;
import com.example.system.entity.WxSession;
import com.example.system.mapper.UserMapper;
import com.example.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yoonada
 * @since 2020-10-28
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final JwtUtil jwtUtil;

    @Override
    public SystemResponse authorizedLogin(AuthorizedLoginDTO authorizedLoginDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", authorizedLoginDTO.getOpenId());
        User user = this.baseMapper.selectOne(wrapper);
        if (user == null) {
//            TODO 没注册  写注册
            User userInfo = User
                    .builder()
                    .openId(authorizedLoginDTO.getOpenId())
                    .avatarUrl(authorizedLoginDTO.getAvatarUrl())
                    .nickName(authorizedLoginDTO.getNickName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            this.baseMapper.insert(userInfo);
            return SystemResponse.response(CommonEnums.WE_CHAT_LOGIN_SUCCESS, getToken(userInfo));
        } else {
            return SystemResponse.response(CommonEnums.WE_CHAT_LOGIN_SUCCESS, getToken(user));
        }
    }

    /**
     * 获取用户的openId
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public SystemResponse getOpenId(String code) throws Exception {
        String openId = getWxOpenId(code);
        return SystemResponse.response(CommonEnums.SUCCESS, openId);
    }

    /**
     * 微信登录
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public SystemResponse wxLogin(String code) throws Exception {
        String openId = getWxOpenId(code);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id",openId);
        User user = this.baseMapper.selectOne(wrapper);
        if (user == null){
            return SystemResponse.response(CommonEnums.LOGIN_NOT_AUTHORIZED_BY_WE_CHAT);
        }else {
            return SystemResponse.response(CommonEnums.WE_CHAT_LOGIN_SUCCESS, getToken(user));
        }
    }

    /**
     * 生成用户的token
     * @param user
     * @return
     */
    private String getToken(User user) {
        Map<String,Object> userMap = new HashMap<>(3);
        userMap.put("uid",user.getUid());
        userMap.put("open_id",user.getOpenId());
        userMap.put("nick_name",user.getNickName());
        return jwtUtil.generateToken(userMap);
    }

    /**
     * 封装一下 获取微信openId
     * @param code
     * @return
     * @throws Exception
     */
    private String getWxOpenId(String code) throws Exception {
        WxSession wxSession = JsonUtil.jsonToPojo(jcode2Session(code), WxSession.class);
        String openId = null;
        if (wxSession != null) {
            openId = wxSession.getOpenid();
        }
        return openId;
    }

    /**
     * 登录凭证校验
     * @param code
     * @return
     * @throws Exception
     */
    private String jcode2Session(String code) throws Exception {
        String sessionInfo = WeChatUtil.jsCode2Session(WeChatConstants.APP_ID, WeChatConstants.SECRET, code, "authorization_code");
        log.info(sessionInfo);
        return sessionInfo;
    }

    /**
     * 获取用户个人信息
     * @return
     */
    @Override
    public SystemResponse getUserInfo() {
        HttpServletRequest request = HttpServletRequestUtil.getHttpServletRequest();
        String uid = (String) request.getAttribute("uid");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        User user = this.baseMapper.selectOne(wrapper);
        return SystemResponse.response(CommonEnums.SUCCESS,user);
    }


}
